package com.chuangke.common.utils;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.github.liaochong.myexcel.utils.FieldDefinition;
import com.github.liaochong.myexcel.utils.ReflectUtil;

public class MyExcelUtils {

	public static Workbook export(Class<?> dataType,List<?> dataList, InputStream template, int startRow) throws Exception {
		if (dataList == null || dataList.isEmpty()) {
			throw new IllegalStateException("导出数据为空！");
		}
		
		Map<Integer, FieldDefinition> fieldMap = ReflectUtil.getFieldDefinitionMapOfExcelColumn(dataType);
		Workbook workbook =  WorkbookFactory.create(template);
        Sheet sheet = workbook.getSheetAt(0);
		Row row;
		Cell cell;
		for (int i = 0; i < dataList.size(); i++) {
			row = sheet.createRow(startRow+i);//sheet.getRow(startRow + i);
			for (Integer index : fieldMap.keySet()) {
				cell = row.createCell(index);
				Object value = fieldMap.get(index).getField().get(dataList.get(i));
				if (value instanceof BigDecimal) {
					cell.setCellValue(value == null ? 0:((BigDecimal) value).doubleValue());
				} else {
					cell.setCellValue(value == null ? "" : value.toString());
				}
			}
		}
		return workbook;
	}
}
